<template>
  <view class="container">
    <ve-card>
      <view class="please">
        <text v-if="pageParams.feeCategory == 1">保养内容</text>
        <text v-else-if="pageParams.feeCategory == 2">维修内容</text>
        <text v-else-if="pageParams.feeCategory == 3">年检内容</text>
        <text v-else-if="pageParams.feeCategory == 4">违章内容</text>
        <view class="c2 fs28" v-if="pageParams.feeCategory == 1 || pageParams.feeCategory == 2" @click="chooseMain">
          <text v-if="pageParams.feeCategory == 1">选择保养内容</text>
          <text v-else-if="pageParams.feeCategory == 2">选择维修内容</text>
          <ve-icon name="arrow_right_0" size="32" style="margin-left: 12rpx; margin-bottom: 4rpx" />
        </view>
      </view>
      <block v-if="pageParams.feeCategory == 1 || pageParams.feeCategory == 2">
        <ve-form ref="ve_form" :model="form" :rules="rules">
          <FeeForm
            :style="form.feeDetailList && form.feeDetailList.length > 0 ? 'margin-bottom: 16rpx;' : ''"
            :title="feeCategoryName"
            :form="item"
            v-for="(item, index) in form.feeDetailList"
            @allAmount="amountoAll"
            @itemNameDelete="itemDelete"
            :key="index"
            :index="index"
          ></FeeForm>
        </ve-form>
      </block>
      <block v-if="pageParams.feeCategory == 3">
        <ve-form ref="ve_form" :model="form" :rules="rules">
          <view class="form-fee-content item-list-3" v-for="(item, index) in form.feeDetailList" :key="index">
            <view class="form-fee-content-title">
              <span class="form-fee-content-title-text">新增费用{{ index + 1 }}</span>
              <view @click="deleteFee(index)">
                <ve-icon name="delete_1" color="rgba(23,22, 22, 1)" size="36" />
              </view>
            </view>
            <view class="form-fee-content-content">
              <ve-form-item label="费用名称" required :prop="`feeDetailList.${index}.itemName`">
                <ve-input v-model="item.itemName" placeholder="请输入" :maxlength="20" />
              </ve-form-item>
              <!-- 年检， 金额必填 -->
              <ve-form-item label="金额" unit="元" required :prop="`feeDetailList.${index}.amount`">
                <ve-input-number :precision="2" placeholder="请输入" v-model="item.amount" :min="0" @blur="amountoAll" :max="99999999.99" />
              </ve-form-item>
              <ve-form-item label="备注" labelPosition="top" :borderBottom="false">
                <ve-input type="textarea" v-model="item.remark" placeholder="请输入" :maxlength="200" />
              </ve-form-item>
            </view>
          </view>
          <view class="ve-form-item-btn ve-form-item-btn-have-data" @click="addNewFee()">
            <ve-icon name="plus" size="30"></ve-icon>
            <span class="ve-form-item-btn-text">新增费用</span>
          </view>
        </ve-form>
      </block>
      <block v-if="pageParams.feeCategory == 4">
        <ve-form ref="ve_form_vio" :model="form" :rules="violationRules">
          <view class="form-fee-content">
            <view class="form-fee-content-content">
              <template v-if="pageParams.feeNameId == 551">
                <ve-form-item label="违章代办真实成本" unit="元" :borderBottom="false">
                  <ve-input-number
                    :precision="2"
                    placeholder="请输入"
                    v-model="form.handleRealCost"
                    :min="0"
                    @blur="violationAmountoAll"
                    @clear="violationAmountoAll"
                    :max="99999999.99"
                  />
                </ve-form-item>
              </template>
              <template v-else>
                <!-- 修改时，罚款必填 -->
                <ve-form-item label="罚款" unit="元" :required="addorEdit != 0" prop="eventAmount">
                  <ve-input-number
                    :precision="2"
                    placeholder="请输入"
                    v-model="form.eventAmount"
                    :min="0"
                    @blur="violationAmountoAll"
                    @clear="violationAmountoAll"
                    :max="99999999.99"
                  />
                </ve-form-item>
                <ve-form-item label="代办费用" unit="元" :borderBottom="false">
                  <ve-input-number
                    :precision="2"
                    placeholder="请输入"
                    v-model="form.handleAmount"
                    :min="0"
                    @blur="violationAmountoAll"
                    @clear="violationAmountoAll"
                    :max="99999999.99"
                  />
                </ve-form-item>
                <ve-form-item v-if="addorEdit == 0" label="违章代办真实成本" unit="元" :borderBottom="false">
                  <ve-input-number
                    :precision="2"
                    placeholder="请输入"
                    v-model="form.handleRealCost"
                    :min="0"
                    @blur="violationAmountoAll"
                    @clear="violationAmountoAll"
                    :max="99999999.99"
                  />
                </ve-form-item>
              </template>
            </view>
          </view>
          <ve-gap size="24" />
          <!-- <ve-form-item label="是否支持违章押金自动抵扣" :borderBottom="false">
            <ve-radio v-model="form.violationDepositType" :list="radioList" />
          </ve-form-item> -->
        </ve-form>
      </block>
    </ve-card>
    <ve-gap size="120"></ve-gap>
    <ve-bottom-box size="mini">
      <view class="bottom-footer">
        <view class="fee-num c1 fs32 fw600">
          <text>合计：</text>
          <text>{{ amount }}</text>
          <text>元</text>
        </view>
        <view class="bottom-line"></view>
        <ve-button type="primary" @click="toConfirm" :loading="okLoading" size="long">{{
          addorEdit == 0 ? '确认添加' : '确认修改'
        }}</ve-button>
      </view>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, computed } from 'vue'
  import FeeForm from './components/fee-form.vue'
  import {
    addAssetFee,
    updateAssetFee,
    getAssetFeeDetail,
    violationFeeDetail,
    violationAddFee,
    violationEditFee,
  } from '@/api/asset/asset-fee'

  const feeCategoryNameArr = ['购置费', '保养项目', '维修项目', '年检项目', '违章项目']

  const pageParams = ref({})
  const feeCategoryName = ref('')
  const amount = ref(0) //总价
  const form = ref({
    feeDetailList: [],
  })
  const addorEdit = ref() //0新增1编辑

  const rules = computed(() => {
    const _rules = {}
    form.value.feeDetailList.forEach((item, index) => {
      // 年检费用名称必填
      if (pageParams.value.feeCategory == 3) {
        _rules[`feeDetailList.${index}.itemName`] = {
          required: true,
          message: '请输入',
        }
      }
      _rules[`feeDetailList.${index}.amount`] = {
        required: true,
        message: '请输入',
      }
    })
    return _rules
  })

  // 违章修改验证
  const violationRules = computed(() => {
    const _rules = {
      eventAmount: {
        required: addorEdit.value != 0 ? true : false,
        message: '请输入',
      },
    }
    return _rules
  })

  onLoad((options) => {
    console.log('pageParams', options)
    addorEdit.value = options.addorEdit
    pageParams.value = options
    feeCategoryName.value = feeCategoryNameArr[options.feeCategory]
    if (options.feeCategory == 4) {
      form.value = {
        id: options.businesId,
        eventAmount: undefined,
        handleAmount: null,
        violationDepositType: 2,
      }
    }
    uni.setNavigationBarTitle({ title: options.id ? '修改费用' : '添加费用' })
    if (options.id) {
      getDetail()
    }
  })
  const violationAmountoAll = () => {
    if (form.value.eventAmount || form.value.handleAmount) {
      amount.value =
        (form.value.eventAmount ? form.value.eventAmount : 0) +
        (form.value.handleAmount ? form.value.handleAmount : 0) -
        (form.value.handleRealCost ? form.value.handleRealCost : 0)
    } else if (form.value.handleRealCost) {
      amount.value = -form.value.handleRealCost
    } else {
      amount.value = 0
    }
  }
  const amountoAll = () => {
    amount.value = 0
    console.log('计算总价', form.value.feeDetailList)
    form.value.feeDetailList.forEach((i, index) => {
      amount.value += i.amount ? i.amount : 0
    })
  }
  // 删除
  const itemDelete = (id) => {
    form.value.feeDetailList.forEach((i, index) => {
      if (i.itemNameId == id) {
        form.value.feeDetailList.splice(index, 1)
      }
    })
  }
  // 年检删除
  const deleteFee = (e) => {
    form.value.feeDetailList.forEach((i, index) => {
      if (e == index) {
        form.value.feeDetailList.splice(index, 1)
      }
    })
    amountoAll()
  }

  const addNewFee = () => {
    form.value.feeDetailList.push({})
  }

  // 获取详情
  const getDetail = () => {
    const d = {
      id: pageParams.value.businesId,
      feeCategory: pageParams.value.feeCategory,
    }
    if (pageParams.value.feeCategory == 4) {
      violationFeeDetail(d).then((res) => {
        if (res.code == 200) {
          const result = res.result
          form.value.id = result.id

          if (result.feeNameId == 55) {
            form.value.eventAmount = result.feeDetailList[0].amount
            form.value.handleAmount = result.feeDetailList[1].amount
          } else if (result.feeNameId == 551) {
            form.value.handleRealCost = result.feeDetailList[0].amount
          }

          form.value.businesId = result.businesId
          form.value.violationDepositType = result.violationDepositType
          violationAmountoAll()
        }
      })
    } else {
      getAssetFeeDetail(d).then((res) => {
        if (res.code == 200) {
          const result = res.result
          form.value.id = result.id
          form.value.businesId = result.businesId
          form.value.feeDetailList = result.feeDetailList
          amountoAll()
        }
      })
    }
  }

  // 去选择保养项目
  const chooseMain = () => {
    var ids = []
    form.value.feeDetailList.forEach((it) => {
      ids.push(it.itemNameId)
    })
    if (pageParams.value.feeCategory == 1) {
      uni.navigateTo({
        url: '/pages/asset/car-maintenance/components/projectList?ids=' + JSON.stringify(ids),
      })
    } else {
      uni.navigateTo({
        url: '/pages/asset/car-repair/components/projectList?ids=' + JSON.stringify(ids),
      })
    }
  }

  // 选完保养项目后
  uni.$on('getMainlists', function (data) {
    if (pageParams.value.feeCategory == 1) {
      const list = data.map((it) => {
        const findFee = form.value.feeDetailList.find((it1) => it1.itemNameId == it.maintenanceProjectId)
        if (findFee) {
          return findFee
        }
        return {
          itemNameId: it.maintenanceProjectId,
          itemName: it.maintenanceName,
          feeUnit: 1,
        }
      })
      form.value.feeDetailList = list
    } else {
      const list = data.map((it) => {
        const findFee = form.value.feeDetailList.find((it1) => it1.itemNameId == it.repairItemId)
        if (findFee) {
          return findFee
        }
        return {
          itemNameId: it.repairItemId,
          itemName: it.repairItem,
          feeUnit: 1,
        }
      })
      form.value.feeDetailList = list
    }
  })

  // 去确认
  const ve_form = ref(null) //保养维修年检的
  const ve_form_vio = ref(null) //违章的

  const okLoading = ref(false)
  const toConfirm = () => {
    var params
    console.log('添加或修改', addorEdit.value)
    if (addorEdit.value == 0) {
      // 新增addAssetFee
      if (pageParams.value.feeCategory == 4) {
        okLoading.value = true
        ve_form_vio.value.validate((valid, errors) => {
          if (valid) {
            params = form.value
            console.log('新增违章', params)
            violationAddFee(params)
              .then((res) => {
                console.log(res)
                okLoading.value = false
                if (res.code == 200) {
                  uni.$emit('refreshData')
                  uni.navigateBack()
                }
              })
              .finally(() => {
                okLoading.value = false
              })
          } else {
            okLoading.value = false
          }
        })
      } else {
        if (form.value.feeDetailList.length == 0 || form.value.feeDetailList == []) {
          return false
        }
        okLoading.value = true
        ve_form.value.validate((valid, errors) => {
          if (valid) {
            params = {
              businesId: pageParams.value.businesId,
              feeDetailList: form.value.feeDetailList,
              feeCategory: pageParams.value.feeCategory,
            }
            // if (pageParams.value.feeCategory == 3) {
            //   params.id = null
            // }
            addAssetFee(params)
              .then((res) => {
                okLoading.value = false
                if (res.code == 200) {
                  uni.$emit('refreshData')
                  uni.navigateBack()
                }
              })
              .finally(() => {
                okLoading.value = false
              })
          } else {
            okLoading.value = false
          }
        })
      }
    } else {
      console.log('pageParams.value.feeCategory', pageParams.value.feeCategory)
      // 修改updateAssetFee
      if (pageParams.value.feeCategory == 4) {
        okLoading.value = true
        // 需处理数据结构
        ve_form_vio.value.validate((valid, errors) => {
          if (valid) {
            let feeList = []
            if (pageParams.value.feeNameId == 551) {
              feeList = [{ itemName: '违章代办真实成本', amount: form.value.handleRealCost }]
            } else {
              feeList = [
                { itemName: '罚款', amount: form.value.eventAmount },
                { itemName: '代办费用', amount: form.value.handleAmount },
              ]
            }

            params = {
              id: pageParams.value.businesId,
              violationDepositType: form.value.violationDepositType,
              feeList,
            }
            violationEditFee(params)
              .then((res) => {
                okLoading.value = false
                if (res.code == 200) {
                  uni.$emit('refreshData')
                  uni.navigateBack()
                }
              })
              .finally(() => {
                okLoading.value = false
              })
          } else {
            console.log('验证error')
            okLoading.value = false
          }
        })
      } else {
        okLoading.value = true
        if (form.value.feeDetailList.length == 0 || form.value.feeDetailList == []) {
          // 确认弹窗
          uni.showModal({
            title: '提示',
            content: '删除全部费项后，费用信息清空，确认删除？',
            success: function (res) {
              if (res.confirm) {
                params = {
                  businesId: form.value.businesId,
                  id: form.value.id,
                  feeDetailList: form.value.feeDetailList,
                  feeCategory: pageParams.value.feeCategory,
                }
                updateAssetFee(params)
                  .then((res) => {
                    okLoading.value = false
                    if (res.code == 200) {
                      uni.$emit('refreshData')
                      uni.navigateBack()
                    }
                  })
                  .finally(() => {
                    okLoading.value = false
                  })
              } else if (res.cancel) {
                console.log('用户点击取消')
                okLoading.value = false
              }
            },
          })
        } else {
          ve_form.value.validate((valid, errors) => {
            if (valid) {
              params = {
                businesId: form.value.businesId,
                id: form.value.id,
                feeDetailList: form.value.feeDetailList,
                feeCategory: pageParams.value.feeCategory,
              }
              updateAssetFee(params)
                .then((res) => {
                  okLoading.value = false
                  if (res.code == 200) {
                    uni.$emit('refreshData')
                    uni.navigateBack()
                  }
                })
                .finally(() => {
                  okLoading.value = false
                })
            } else {
              okLoading.value = false
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    height: auto;
    min-height: 100%;
    padding: 24rpx;
  }
  .please {
    height: 92rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .bottom-line {
    width: 100%;
    height: 2rpx;
    transform: scaleY(0.5);
    background: rgba(216, 216, 216, 0.3);
    margin: 32rpx 0;
  }
  .bottom-footer {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
  }
  .fee-num {
    display: flex;
    align-items: flex-end;
    justify-content: flex-start;
    text:nth-child(2) {
      font-size: 48rpx;
      color: #fe615a;
      line-height: 1;
    }
    text:nth-child(3) {
      font-size: 24rpx;
      color: #fe615a;
      margin-left: 8rpx;
    }
  }

  .form-fee-content {
    width: 654rpx;
    background: #f7f8fa;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    opacity: 1;
    .form-fee-content-title {
      height: 88rpx;
      box-sizing: border-box;
      padding: 0 24rpx 0 24rpx;
      background: #f0f1f3;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .form-fee-content-title-text {
      font-size: 30rpx;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #191c27;
    }
    .form-fee-content-content {
      box-sizing: border-box;
      padding: 0 24rpx 0 24rpx;
    }
  }
  .item-list-3 {
    margin-bottom: 24rpx;
  }
  .ve-form-item-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 88rpx;
    background: #f3f7ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    opacity: 1;
    border: 2rpx solid #3072f6;
    .ve-form-item-btn-text {
      font-size: 30rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #3072f6;
      margin-left: 18rpx;
    }
  }
  .ve-form-item-btn-have-data {
    margin-bottom: 24rpx;
  }
  :deep(.ve-textarea) {
    background: #e6e7ea !important;
  }
</style>
